package joc;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import joc.util.ObjectMapper;

public class Cache {
	private final static Map<Long, Annotation> annotationCache = new HashMap<Long, Annotation>();
	private final static Map<Long, Method> methodCache = new HashMap<Long, Method>();
	private final static ObjectMapper<String, Object> postConditionCache = new ObjectMapper<String, Object>();
	
	public static void savePostCondition(Object obj, String key, Object postCondition) {
		postConditionCache.put(obj, key, postCondition);
	}
	
	public static boolean containsPostCondition(Object obj, String key) {
		return postConditionCache.contains(obj);
	}
	
	public static Object getPostCondition(Object obj, String key) {
		return postConditionCache.get(obj, key);
	}
	
	public static long saveAnnotation(Annotation annotation) {
		long key = getKeyForCache(annotationCache);
		annotationCache.put(Long.valueOf(key), annotation);
		return key;
	}
	
	public static Annotation getAnnotation(long key) {
		return annotationCache.get(Long.valueOf(key));
	}
	
	public static long saveMethod(Method method) {
		long key = getKeyForCache(methodCache);
		methodCache.put(Long.valueOf(key), method);
		return key;
	}
	
	public static Method getMethod(long key) {
		return methodCache.get(Long.valueOf(key));
	}
	
	private static long getKeyForCache(Map<Long, ?> cache) {
		long key;
		do {
			key = (long) ((Math.random() - 0.5) * 2 * Long.MAX_VALUE);
		} while (cache.containsKey(Long.valueOf(key)));
		return key;
	}
	

}
